<template>
  <div class="hostel">
    <div class="search">
      位置：
      <el-input
        style="width: 145px; padding-right:10px"
        placeholder="请输入位置"
        prefix-icon="el-icon-search"
        v-model="searchData.localtion">
      </el-input>

      所属人：
      <el-select style="width: 180px;" v-model="searchData.userId" placeholder="请选择所属人">
        <el-option
          v-for="item in userOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>

      <el-button style=" float: right; margin-left:10px;" @click="reset">重置</el-button>
      <el-button style=" float: right;" type="primary" @click="onSubmit">查询</el-button>
    </div>

    <div class="do">
      <el-button style="margin-left:10px;" v-if="user.position === 1 || user.position === 2" @click="dialogFormVisible = true">新增</el-button>
      <el-button v-if="user.position === 2" @click="batchDelete()">批量删除</el-button>
    </div>

    <el-table
    ref="multipleTable"
    :data="tableData"
    tooltip-effect="dark"
    style="width: 100%"
    stripe
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="parkingNumber"
      label="车位号">
    </el-table-column>
    <el-table-column
      prop="location"
      label="位置">
    </el-table-column>
    <el-table-column
      prop="username"
      label="所属人">
    </el-table-column>
    <el-table-column
      prop="status"
      label="状态"
      :filters="[{ text: '未出售', value: 0 }, { text: '已出售', value: 1 }]"
      :filter-method="filterTag"
      filter-placement="bottom-end">
      <template slot-scope="scope">
          <el-tag
          :type="scope.row.status === 0 ? 'primary' : 'success'"
          disable-transitions>{{getStatusText(scope.row.status)}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column v-if="user.position === 2 || user.position === 1" label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          v-if="user.position === 2"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 20px; text-align: right; margin-right: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>

    <ParkingFormPop class="houseFormPop" @updateFormData="updateFormData" :userOptions="userOptions" :title="title" :formData="updateTableData" v-show="dialogFormVisible" :visible.sync="dialogFormVisible"></ParkingFormPop>
  </div>
</template>
         
<script>
import api from '@/api';
import { cloneDeep } from 'lodash';
import ParkingFormPop from './ParkingFormPop.vue';
  import { mapState,mapMutations } from "vuex"


export default {
  computed:{
      ...mapState("login",["user"])
    },
    components: {
      ParkingFormPop,
    },
    data() {
      return {
        userOptions:[],
        options:[],
        title: '新增车位',
        currentPage: 1,
        total:100,
        pageSize:10,
        dialogFormVisible: false,
        searchData:{
          pageNow: 1,
        },
        tableData: [{
          id:'',
          userId:'',
          username:'',
          parkingNumber: '001',
          location:'B区',
          status: 0
        }],
        selectedRow:[],
        updateTableData:{
          id:'',
          userId:'',
          parkingNumber: '',
          location:'',
          status: 0
        }
      }
    },
    methods: {
      updateFormData(data){
        this.updateTableData = data;
      },
      getStatusText(sex){
        switch(sex){
            case 0 : return '未出售';
            case 1 : return '已出售';
          default : return '';
          }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.searchData.pageNow = val
        //获取房屋信息
        this.onSubmit();
      },
      handleSelectionChange(selection) {
          this.selectedRow = selection
      },
      handleEdit(index, row) {
        this.updateTableData = row;
        this.dialogFormVisible = true;
        this.title = '编辑车位'
      },
      handleDelete(index, row) {
        api.parkDelete(row.id).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              this.tableData.splice(index,1)
              this.$message.success('删除成功');
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      filterTag(value, row) {
        return row.sex === value;
      },
      filterTag1(value, row) {
        return row.position === value;
      },
      //批量删除
      batchDelete(){
        var deleteIds = '';
        this.selectedRow.map(item =>{
          if(deleteIds === ''){
            deleteIds = item.id
          }else{
            deleteIds = deleteIds + "," + item.id
          }
        })
        if(deleteIds === ''){
          this.$message.error("请勾选删除项")
          return;
        }
        api.parkDelete(deleteIds).then(res =>{
            if(res.type === 'error'){
                this.$message.error(res.message)
            }else if(res.data.code === 200){
              this.$message.success('删除成功');
              this.selectedRow.map(item =>{
                const index = this.tableData.findIndex((data) => data.id === item.id);
                this.tableData.splice(index,1)
              })
            }else{
              this.$message.error(res.data.message)
            }
        })
      },
      onSubmit() {
        //获取车位信息
        api.parkList(this.searchData).then(res => {
              if (res.type === 'error') {
                this.$message.error(res.message);
              } else if (res.data.code === 200) {
                let parkInfoDTO = res.data.data.parkInfos;

                const userMap = new Map(this.userOptions.map(option => [option.value, option.label]));

                 parkInfoDTO.forEach(item => {
                    if(item.userId){
                      item.username = userMap.get(item.userId);
                    }
                  });
                  if(this.searchData.userId){
                        parkInfoDTO = parkInfoDTO.filter(item => 
                          item.userId && item.userId === this.searchData.userId
                        );
                  }                
                this.tableData = parkInfoDTO;
                this.total = res.data.data.total
              } else {
                this.$message.error(res.data.message);
              }
        });

      },
      // 重置
      reset(){
        this.searchData.localtion = '',
        this.searchData.userId = '',
        this.onSubmit();
      },
      //获取用户信息
      getUserByPosition(){
        return new Promise((resolve, reject) => {
            api.getUserByPosition(false,false,{}).then(res => {
                  if (res.type === 'error') {
                    this.$message.error(res.message);
                    reject(res.message);
                  } else if (res.data.code === 200) {
                    let userList = res.data.data.userList;

                    userList = userList.filter(item => item.position !== 4)

                    this.userOptions = userList.map(item => ({
                        value: item.id,
                        label: item.username
                    }));
                    resolve();
                  } else {
                    this.$message.error(res.data.message);
                    reject(res.data.message);
                  }
            });
        })
      },
    },
    created () {
        //获取房屋信息
        this.getUserByPosition().then(() => {
            this.onSubmit(); 
        });
    }
}
</script>
<style scoped>
.hostel{
  background-color: #fff;
}
.hostel .search{
  padding: 10px;
}
.hostel .do{
  padding: 10px;
}
/* 自定义遮罩层样式 */
.hostel .houseFormPop {
  background-color: rgba(0, 0, 0, 0.5); /* 遮罩层颜色 */
  z-index: 9999; /* 设置一个较高的 z-index 使遮罩层位于最上层 */
}
</style>